const Base = require('./base.js');
const { think } = require('thinkjs');
const fs = require('fs');
const moment = require('moment');

module.exports = class extends Base {
  async bannerAction() {
    const model = this.model('banner');
    const data = await model.order(['sort DESC']).where({type:2}).select();

    return this.success(data);
  }
  async getCateAction(){
    const model = this.model('news_cate');
    const data = await model.order(['id DESC']).select();

    return this.success(data);
  }
  async getNewsListAction(){
    const page = this.get('page') || 1;
    const size = this.get('size') || 20;

    const model = this.model('news_list');
    const data = await model.order(['id DESC']).field(['thumb', 'title', 'id', 'read']).where({cate_id: this.get('cateId')}).page(page, size).countSelect();

    return this.success(data);
  }

  async getNewsDetailAction(){
    const model = this.model('news_list');
    const data = await model.where({id: this.get('id')}).find();
    await model.where({id: this.get('id')}).increment('read', 1)

    return this.success(data);
  }
  async getActvityListAction(){
    const page = this.get('page') || 1;
    const size = this.get('size') || 20;

    const model = this.model('activity_list');
    const data = await model.order(['id DESC']).field(['thumb', 'title', 'id', 'num']).page(page, size).countSelect();

    return this.success(data);
  }
  async getActvityDetailAction(){
    const model = this.model('activity_list');
    const data = await model.where({id: this.get('id')}).find();

    return this.success(data);
  }

  async joinActvityAction(){
    const id = this.get('id')
    
    const data = await this.model('activity_apply').where({
      activity_id: id,
      user_id: this.getLoginUserId()
    }).find()

    if(!think.isEmpty(data)){
      return this.fail(408, '请勿重复报名');
    }

    await this.model('activity_apply').add({
      activity_id: id,
      user_id: this.getLoginUserId(),
      create_time: ['exp', 'CURRENT_TIMESTAMP()']
    });
    return this.success();
  }
  
  async uploadImgAction() {
    const brandFile = this.file('file');
    if (think.isEmpty(brandFile)) {
      return this.fail('保存失败');
    }
    const that = this;
    const filename = '/static/auth/' + think.uuid(32) + '.jpg';
    const is = fs.createReadStream(brandFile.path);
    const os = fs.createWriteStream(think.ROOT_PATH + '/www' + filename);
    is.pipe(os);

    return that.success({
      name: 'pic',
      url: think.config('baseUrl') + filename
    });
  }
  async authSelectDataAction(){
    const data1 = await this.model('dict_item').where({type: 'identity_type'}).select();
    const data2 = await this.model('dict_item').where({type: 'position_type'}).select();

    return this.success({
      identity: data1,
      position: data2
    });
  }
  async saveAuthApplyAction(){
    const values = this.post();
    const model = this.model('figure_apply');

    const hasApply = await model.where({user_id: this.getLoginUserId()}).find()

    if(!think.isEmpty(hasApply)){
      if(hasApply.status === 0){
        await model.where({user_id: this.getLoginUserId()}).limit(1).delete();
      }else{
        return this.fail(409, '请勿重复申请');
      }
      
    }

    const hasFigure = await this.model('figure').where({name: values.name, user_id: 0}).select();

    const data = values
    data.user_id = this.getLoginUserId()
    data.create_time = ['exp', 'CURRENT_TIMESTAMP()']
    if(data.industry === '请选择'){
      data.industry = ''
    }
    if(data.round === '请选择'){
      data.industry = ''
    }
    await model.add(data);

    return this.success(hasFigure);
  }
  async submitAuthApplyAction(){
    const values = this.post();
    const model = this.model('figure_apply');
    const apply = await model.where({user_id: this.getLoginUserId()}).find()
    if(think.isEmpty(apply)){
      return this.fail(409, '找不到申请');
    }
    if(apply.status !== 1){
      return this.fail(409, '找不到申请');
    }
    if(think.isEmpty(values)){
      await model.where({user_id: this.getLoginUserId()}).update({
        status: 2
      })
    }else{
      values.status = 2
      delete values.user_id
      delete values.create_time
      await model.where({user_id: this.getLoginUserId()}).update(values)
    }
    return this.success();
  }
  async confirmAuthApplyAction(){
    const id = this.get('figureId');
    const model = this.model('figure_apply');
    if(think.isEmpty(id)){
      await model.where({user_id: this.getLoginUserId()}).update({
        status: 1
      })
    }else{
      await model.where({user_id: this.getLoginUserId()}).update({
        status: 1,
        figure_id: id
      })
    }
    return this.success();
  }
  async authApplyDetailAction(){
    const model = this.model('figure_apply');
    let detail = await model.where({user_id: this.getLoginUserId()}).find()
    if(think.isEmpty(detail)){
      return this.fail(409, '找不到数据');
    }
    if(detail.figure_id){
      detail = await this.model('figure').where({id: detail.figure_id}).find()
    }
    const industry = await this.model('dict_item').where({type: 'industry_type'}).select();
    const round = await this.model('dict_item').where({type: 'round_type'}).select();
    return this.success({
      detail: detail,
      industry: industry,
      round: round
    });
  }
  async getAuthApplyAction(){
    const model = this.model('figure_apply');
    let detail = await model.field(['status', 'pay_status']).where({user_id: this.getLoginUserId()}).find()
    return this.success(detail);
  }

  async payAction(){

    const detail = await this.model('figure_apply').field(['status', 'pay_status']).where({user_id: this.getLoginUserId()}).find()

    if(detail.status !==3 && detail.status !== 4){
      return this.fail('请先认证');
    }

    const openid = await this.model('user').where({ id: this.getLoginUserId() }).getField('weixin_openid', true);

    if (think.isEmpty(openid)) {
      return this.fail('微信支付失败');
    }

    const month = this.get('num')
    const level = this.get('level')

    if(month!=6 && month!=12){
      return this.fail('参数有误');
    }

    const setMoney = await this.model('set').find()

    let money = 0

    if((detail.status === 3 || detail.pay_status === 1) && month == 6){
      // money = 300
      money = setMoney.vip6
    }
    if((detail.status === 4 || detail.pay_status === 2) && month == 6){

      // money = 2000
      money = setMoney.svip6

      if(detail.status === 4 && level == 1){
        // money = 300
        money = setMoney.vip6
      }
      if(detail.status === 4 && level == 2){
        // money = 2000
        money = setMoney.svip6
      }
    }
    if((detail.status === 3 || detail.pay_status === 1) && month == 12){
      // money = 500
      money = setMoney.vip12
    }
    if((detail.status === 4 || detail.pay_status === 2) && month == 12){
      // money = 3000
      money = setMoney.svip12

      if(detail.status === 4 && level == 1){
        // money = 500
        money = setMoney.vip12
      }
      if(detail.status === 4 && level == 2){
        // money = 3000
        money = setMoney.svip12
      }
    }

    const orderSn = this.model('order').generateOrderNumber();

    let logLevel = 0
    let logType = 0

    switch(true){
      case detail.status === 3 && detail.pay_status === 0:
        logLevel = 1
        logType = 1
        break;
      case detail.status === 4 && level == 2 && detail.pay_status === 0:
        logLevel = 2
        logType = 1
        break;
      case detail.status === 4 && level == 1 && detail.pay_status === 0:
        logLevel = 1
        logType = 1
        break;
      case detail.pay_status === 1:
        logLevel = 1
        logType = 2
        break;
      case detail.pay_status === 2:
        logLevel = 2
        logType = 2
        break;
    }

    await this.model('pay_log').add({
      out_trade_no: orderSn,
      pay_status: 0,
      time: month,
      create_time: ['exp', 'CURRENT_TIMESTAMP()'],
      user_id: this.getLoginUserId(),
      total: money,
      level: logLevel,
      type: logType
    })

    const WeixinSerivce = this.service('weixin', 'api');
    try {
      const returnParams = await WeixinSerivce.createUnifiedOrder({
        openid: openid,
        body: '订单编号：' + orderSn,
        out_trade_no: orderSn,
        total_fee: parseInt(money * 100),
        spbill_create_ip: this.ctx.ip
      });
      return this.success(returnParams);
    } catch (err) {
      return this.fail('微信支付失败');
    }
  }

  async sendRequestAction(){

    const type = this.get('type');

    let count = await this.model('apply').where({create_time: ['between', `${moment().startOf('day').format("YYYY-MM-DD HH:mm:ss")}, ${moment().endOf('day').format("YYYY-MM-DD HH:mm:ss")}`], user_id: this.getLoginUserId()}).select();
    if(!think.isEmpty(count)){
      const has_apply = count.some(item=>{
        return item.figture == this.get('id')
      })
      if(!think.isEmpty(has_apply)){
        return this.success();
      }else{
        const num = await this.model('set').find();
        if(count.length >= num.num){
          return this.fail(409, '您的请求超出当日限制');
        }
      }
    }

    const user = await this.model('user').where({id: this.getLoginUserId()}).find()
    const data = {
      user_name: user.name,
      company: user.company,
      position: user.position,
      figture: this.get('id'),
      user_id: this.getLoginUserId(),
      create_time: ['exp', 'CURRENT_TIMESTAMP()'],
      type: type
    }
    await this.model('apply').add(data)
    return this.success();
  }

  async getSysMoneyAction(){
    const data = await this.model('set').find()
    return this.success(data);
  }
};
